//
//  SWBookManager.swift
//  YiyaPuzzleDemo
//
//  Created by linhan on 16/9/29.
//  Copyright © 2016年 test. All rights reserved.
//

import Foundation
private let _manager:SWBookManager = SWBookManager()
class SWBookManager: NSObject,SWAPIComponent
{
//    private var _dataPath:String{
//        return (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).valueAt(0) ?? "") + "/books.data"
//    }
    
    private var _dataPath:String = ""
    var baseDirectory:String = ""
    
    private var _setup:Bool = false
    private var _fileManager = FileManager.default
    var book:SWBook?
    
    //本地保存的书本模板
    var books:[SWBook] = []
    
    private var _history:SWBooks?
    
    var setupedCallback:(()->Void)?
    
    class func sharedManager() -> SWBookManager
    {
        return _manager
    }
    
    var setuped:Bool{
        return _setup
    }
    
    override init()
    {
        super.init()
        baseDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).valueAt(0) ?? ""
        baseDirectory += "/book"
        _dataPath = "\(baseDirectory)/books.data"
        
        trace(baseDirectory)
        
        if !_fileManager.fileExists(atPath: baseDirectory)
        {
            try? _fileManager.createDirectory(atPath: baseDirectory, withIntermediateDirectories: true, attributes: nil)
        }
    }
    
    func setup()
    {
        if !_setup
        {
            //先加载本地数据，再加载网络数据，再进行合并保存
            let history:SWBooks = SWCacheManager.sharedManager().readCache(_dataPath) as? SWBooks ?? SWBooks()
            history.books = history.books ?? []
            if let ids = history.books as? [String]
            {
                for bookID in ids
                {
                    let dataPath:String = "\(baseDirectory)/\(bookID).data"
                    if let book = SWCacheManager.sharedManager().readCache(dataPath) as? SWBook
                    {
                        books.append(book)
                    }
                }
            }//end data
            print("books index:", books.map({$0.index}), books.map({$0.title}))
            books.sort(by: {$0.index < $1.index})
            _history = history
            saveHistory()
            
            _setup = true
            
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "BookManagerSetupComplete"), object: nil)
            setupedCallback?()
            
            fetchBookList()
            
            SWBookAssetManager.sharedManager().launch()
            SWDownloadManager.sharedManager().launch()
            SWPageManager.sharedManager().launch()
        }//end setup
    }
    
    func fetchBookList()
    {
        let req = SWBookListFetchReq()
        req.successCallback = {[weak self] response,_ in
            if let response = response as? SWBookListFetchRsp,
               let list = response.books,list.count > 0
            {
                let templates:[SWBookTemplate] = list.map({SWBookTemplate(response: $0)})
                //如果本地模板数据不全或者本地模板数据较旧，则从线上进行更新
                for (index,template) in templates.enumerated()
                {
                    if let index = self?.books.index(where: {($0.templateID ?? "") == (template.templateID ?? "")}),
                        let book = self?.books.valueAt(index), book.version >= template.version
                    {
                        book.index = index
                        continue
                    }
                    
                    if let templateID = template.templateID,templateID != ""
                    {
                        self?.fetchBookTemplate(templateID:templateID, index:index)
                    }
                }
                
                
            }//end if response
        }
        load(req)
    }
    
    //获取并保存模板
    func fetchBookTemplate(templateID:String, index:Int)
    {
        print("fetchBookTemplate:", templateID)
        let req = SWBookTemplateFetchReq()
        req.id = templateID
        req.successCallback = {[weak self] response,_ in
            if let bookResponse = (response as? SWBookTemplateFetchRsp)?.book
            {
                let template:SWBookTemplate = SWBookTemplate(response: bookResponse)
                if let index = self?.books.index(where: {($0.templateID ?? "") == (template.templateID ?? "")}),
                    let book = self?.books.valueAt(index), book.version < template.version
                {
                    book.index = index
                    book.updateFromTemplate(template)
                    self?.saveBookData(book)
                }
                else
                {
                    if let book = self?.createBook(template)
                    {
                        book.index = index
                        self?.addBook(book)
                        self?.saveBookData(book)
                    }
                }
            }
        }
        load(req)
    }
    
    //网络与本地合并
    func merge(_ books:[SWBook])
    {
        
    }
    
    //新增书本(根据对应书本的模板创建一本新书)
    func createBook(_ template:SWBookTemplate) -> SWBook
    {
        let templateID:String = template.templateID ?? "default"
        let category = template.category
        let book:SWBook = SWBook()
        book.bookID = templateID
        book.templateID = templateID
        book.title = template.title
        book.category = template.category
        if let pageTemplates = template.pages?.flatMap({$0 as? SWPageTemplate})
        {
            var pages:[SWPage] = []
            for template in pageTemplates
            {
                let page = SWPage(template: template)
                page.bookID = templateID
                page.category = category
                pages.append(page)
            }
            book.pages = pages
        }
        return book
    }
    
    //通过服务端API根据对应模板创建了一本新书，然后加入到本地缓存
    func addBook(_ book:SWBook)
    {
        guard let bookID = book.bookID, bookID != "" else{
            return
        }
        
        if var books = _history?.books as? [String]
        {
            if let index = books.index(where: {$0 == book.bookID})
            {
                books[index] = bookID
            }
            else
            {
                books.append(bookID)
            }
            _history?.books = books
            saveHistory()
        }
        
        if !books.contains(where: {($0.bookID ?? "") == (book.bookID ?? "")})
        {
            books.append(book)
            books.sort(by: {$0.index < $1.index})
        }
    }
    
    //进行编辑某本书
    func editingBook(_ book:SWBook)
    {
        if self.book != book
        {
            self.book = book
            //SWBookAssetManager.sharedManager().setBook(book.bookID)
            //下载页面背景模板、以及合成效果图
            setTimeout(1, closure: {[weak self] in
                self?.preloadBookAssets(book)
            })
            
        }
    }
    
    func fetchBook(bookID:String) -> SWBook?
    {
        if let index = books.index(where: {($0.bookID ?? "") == bookID}),
            let book = books.valueAt(index)
        {
            return book
        }
        return nil
    }
    
    func fetchPage(book:SWBook, pageID:String) -> SWPage?
    {
        if let pages:[SWPage] = book.pages?.flatMap({$0 as? SWPage}),
            let index = pages.index(where: {($0.pageID ?? "") == pageID}),
            let page = pages.valueAt(index)
        {
            return page
        }
        return nil
    }
    
    func fetchPage(bookID:String, pageID:String) -> SWPage?
    {
        if let book = fetchBook(bookID: bookID)
        {
            return fetchPage(book:book, pageID:pageID)
        }
        return nil
    }
    
    //保存当前正在编辑的书
    func save(page:SWPage)
    {
        guard let bookID = page.bookID,bookID != "",
              let index = books.index(where: {($0.bookID ?? "") == bookID}),
              let book = books.valueAt(index) else{
            return
        }
        
        saveBookData(book)
    }
    
    private func saveBookData(_ book:SWBook)
    {
        if let bookID = book.bookID, bookID != ""
        {
            let dataPath:String = "\(baseDirectory)/\(bookID).data"
            SWCacheManager.sharedManager().writeCache(book, path: dataPath)
        }
    }
    
    //加载
    private func preloadBookAssets(_ book:SWBook)
    {
        if let pages:[SWPage] = book.pages?.flatMap({$0 as? SWPage})
        {
            for page in pages
            {
                //如果此页不是自己所能编辑的，则只显示预览图即可
                if let URL = page.previewResultURL
                {
                    let task1 = SWDownloadTask(url: URL)
                    SWDownloadManager.sharedManager().addTask(task1)
                    //continue
                }
                
                //加载背景小图
                if let URL = page.previewBgURL
                {
                    let task1 = SWDownloadTask(url: URL)
                    SWDownloadManager.sharedManager().addTask(task1)
                }
                
                //加载背景大图
                if let URL = page.largeBgURL
                {
                    let task1 = SWDownloadTask(url: URL)
                    SWDownloadManager.sharedManager().addTask(task1)
                }
                
            }//END FOR
        }//END pages
        
    }
    
    private func saveHistory()
    {
        if let history = _history
        {
            SWCacheManager.sharedManager().writeCache(history, path: _dataPath)
        }
    }
    
}
